class PronunciationService {
  constructor() {
    this.isPlaying = false;
    this.audioProcess = null;
  }

  /**
   * Prepare pronunciation audio for a word
   * @param {string} audioPath - Path to the audio file
   * @returns {Promise} - Promise that resolves with audio information
   */
  async playPronunciation(audioPath) {
    // Validate that an audio path is provided
    if (!audioPath) {
      throw new Error('No audio path provided');
    }

    // For online resources or local files, we just need to return the path
    // The frontend will handle the actual playback using HTML5 audio element
    console.log(`Returning audio path for playback: ${audioPath}`);

    return {
      success: true,
      message: 'Ready to play pronunciation',
      data: { audioPath },
    };
  }

  /**
   * Stop current pronunciation playback
   */
  stopPronunciation() {
    // Stopping is handled on the frontend side with the HTML5 audio element
    console.log('Stop pronunciation requested');
    return { success: true, message: 'Stop requested' };
  }

  /**
   * Get pronunciation file path for a word
   * @param {Object} wordData - Word data containing pronunciation paths
   * @param {string} type - Type of pronunciation (uk or us)
   * @returns {string|null} - Path to the pronunciation file or null if not available
   */
  getPronunciationPath(wordData, type = 'uk') {
    let audioPath = null;

    if (type === 'uk' && wordData.uk_speech) {
      audioPath = wordData.uk_speech;
    } else if (type === 'us' && wordData.us_speech) {
      audioPath = wordData.us_speech;
    } else {
      // Fallback to any available pronunciation
      audioPath = wordData.uk_speech || wordData.us_speech;
    }

    return this.processAudioPath(audioPath);
  }

  /**
   * Process audio path by removing quotes and fixing escaped characters
   * @param {string} audioPath - Raw audio path
   * @returns {string} - Processed audio path
   */
  processAudioPath(audioPath) {
    if (audioPath) {
      // Remove surrounding quotes if present
      if (audioPath.startsWith('"') && audioPath.endsWith('"')) {
        audioPath = audioPath.slice(1, -1);
      }

      // Fix escaped forward slashes
      audioPath = audioPath.replace(/\\\//g, '/');
    }

    return audioPath;
  }

  /**
   * Check if pronunciation is available for a word
   * @param {Object} wordData - Word data containing pronunciation paths
   * @returns {boolean} - True if pronunciation is available
   */
  isPronunciationAvailable(wordData) {
    return !!(wordData.uk_speech || wordData.us_speech);
  }
}

module.exports = PronunciationService;
